// 1.移除数组 [1, 2, 3, 4, 2] 中的2。不要直接修改数组，结果返回新的数组
let arr1 = [1, 2, 3, 4, 2];
let newArray1 = [];
for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] != 2) {
        newArray1.push(arr1[i]);
    }
}
console.log(newArray1);

// 2.定义一个函数,能在数组 [1, 2, 3, 4, 2] 的 "2"后面添加元素 "JavaScript"。不要直接修改数组 arr，结果返回新的数组

let arr2 = [1, 2, 3, 4, 2];
let newArray2 = [];
for (let i = 0; i < arr1.length; i++) {
    newArray2.push(arr2[i]);

    if (arr2[i] === 2) {
        newArray2.push('JavasCript');
    }
}
console.log(newArray2);

// 3.统计数组 [1, 2, 3, 4, 2] 中2出现的次数

let arr3 = [1, 2, 3, 4, 2];
let time3 = 0;
for (let i = 0; i < arr3.length; i++) {
    if (arr3[i] === 2) time3++;
}
console.log(time3);

// 4.找出数组 [1, 2, 3, "JavaScript", 4, "JavaScript", 2, 4, "JavaScript"] 中重复出现过的元素,并用数组将重复元素装起来输出

let arr4 = [1, 2, 3, 'JavaScript', 4, 'JavaScript', 2, 4, 'JavaScript'];
let newArray4 = [];
for (let i = 0; i < arr4.length; i++) {
    if (arr4.includes(arr4[i], i + 1)) {
        newArray4.push(arr4[i]);
    }
}
console.log(newArray4);

// 5.在数组里面输出年龄小于17的对象
let arr5 = [
    {
        name: '111',
        sex: 'boy',
        age: 18,
    },
    {
        name: '222',
        sex: 'girl',
        age: 17,
    },
    {
        name: '333',
        sex: 'boy',
        age: 16,
    },
    {
        name: '444',
        sex: 'girl',
        age: 15,
    },
    {
        name: '555',
        sex: 'boy',
        age: 20,
    },
];
let newArray5 = [];
for (let i = 0; i < arr5.length; i++) {
    if (arr5[i].age < 17) {
        newArray5.push(arr5[i]);
    }
}
console.log(newArray5);

// 6. 数组扁平化, 把数组[1, [2, [3, 4, 5]]]转成[1, 2, 3, 4，5]
let arr6 = [1, [2, [3, 4, 5]]];
console.log(arr6.flat(Infinity));

// 7. 使用reduce实现[1,2,3,4,9]数组中所有成员的和
const arr7 = [1, 2, 3, 4, 9];
const sum7 = arr7.reduce(function (accumulator, current) {
    return accumulator + current;
}, 0);
console.log(sum7);
// 8. 数组去重的方法 (4种)
//
let arr8 = [1, 2, 3, 1, 5, 8, 7, 5, 6, 4, 2];
// 1.每次循环是否能查找与当前索引值相对应的值，有就splice
for (let i = 0; i < arr8.length; i++) {
    if (arr8.indexOf(arr8[i], i + 1) != -1) {
        arr8.splice(arr8.indexOf(arr8[i], i + 1), 1);
        i--;
    }
}
// console.log(arr8);
// 2.用另一个数组去检查是否有重复
let newArray8 = [];
for (let i = 0; i < arr8.length; i++) {
    for (let j = 0; j < newArray8.length; j++) {
        if (arr8[i] != newArray8[j]) {
            newArray8.push(arr8[i]);
            break;
        }
    }
}
// console.log(arr8);
// 3.includes
for (let i = 0; i < arr8.length; i++) {
    for (let j = i + 1; j < arr8.length; j++) {
        if (arr8.includes(arr8[i], j)) {
            arr8.splice(j, 1);
            i--;
            break;
        }
    }
}
// console.log(arr8);
// 4.reduce
const newArray81 = arr8.reduce(function (accumulator, current) {
    if (!accumulator.includes(current)) {
        accumulator.push(current);
    }
    return accumulator;
}, []);
console.log(newArray81);
